﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Hont.UMotionGraph
{
    public abstract class MoGraphTransformContainer : MonoBehaviour, IMoGraphContainer
    {
        public Transform[] elements;
        public MoGraphEffector[] effectors;
        protected List<IMoGraphEffector> mEffectorList;
        protected Vector3[] mUpdateMiddleValueArr;
        protected Vector3[] mSourceValueArr;

        List<IMoGraphEffector> IMoGraphContainer.EffectorList { get { return mEffectorList; } }

        public virtual int Count { get { return elements.Length; } }

        public abstract void UpdateValue(Vector3[] values);


        protected virtual void Awake()
        {
            mEffectorList = new List<IMoGraphEffector>();
            mEffectorList.AddRange(effectors);
            mEffectorList.ForEach(m => m.Init(this));

            mUpdateMiddleValueArr = new Vector3[elements.Length];
            mSourceValueArr = new Vector3[elements.Length];
            for (int i = 0; i < mSourceValueArr.Length; i++)
            {
                mSourceValueArr[i] = elements[i].position;
            }
        }

        protected virtual void Update()
        {
            for (int i = 0; i < mUpdateMiddleValueArr.Length; i++)
            {
                mUpdateMiddleValueArr[i] = GetValue(0, i);
            }

            for (int i = 0; i < mEffectorList.Count; i++)
            {
                var item = mEffectorList[i];

                for (int j = 0; j < elements.Length; j++)
                {
                    mUpdateMiddleValueArr[j] = item.Execute(j, mUpdateMiddleValueArr[j]);
                }
            }

            UpdateValue(mUpdateMiddleValueArr);
        }

        public virtual Vector3 GetValue(int type, int inx)
        {
            return mSourceValueArr[inx];
        }
    }
}
